#include "foc_mainwindow.h"
#include "ui_foc_mainwindow.h"
#include <iostream>
#include <QString>
#include <QSerialPortInfo>
#include <QList>
#include <QHostInfo>
#include <QNetworkInterface>
#include <QDebug>

FocMainWindow::FocMainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::FocMainWindow)
{
    ui->setupUi(this);
    this->init_var();
    this->init_ui();
    this->protocol_tim = new QTimer(this);
    this->protocol_tim->setSingleShot(false);
    this->protocol_tim->setInterval(500);
    this->protocol_tim->start();
    this->init_signal_and_slot();
}

void FocMainWindow::init_var()
{
    this->parser = nullptr;
    this->serial = nullptr;
    this->tcp_server = nullptr;
    this->tcp_socket = nullptr;
}

/**
 * @brief  初始化一部分 ui 组件
 */
void FocMainWindow::init_ui()
{
    /* 获取所有 ip */
    QList<QHostAddress> all_ip = QNetworkInterface::allAddresses();
    for (QList<QHostAddress>::iterator it = all_ip.begin(); it != all_ip.end(); ++it) {
        QHostAddress addr = *it;
        if (addr.protocol() == QAbstractSocket::IPv4Protocol) {
            QString ip = addr.toString();
            ui->cbb_tcp_ip->addItem(ip);
        }
    }

    /* 获取所有串口 */
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        if(nullptr == this->serial) {
            this->serial = new QSerialPort(this);
        }

        this->serial->setPort(info);
        ui->cbb_serial_port->addItem(this->serial->portName());
    }

    ui->gb_tcp_connect->setEnabled(false);
}

void FocMainWindow::tcp_connected()
{
    std::cout << "tcp_connected" << std::endl;
}

void FocMainWindow::tcp_disconnected()
{
    this->tcp_socket->deleteLater();
}

// void FocMainWindow::tcp_state_changed()
// {

// }

void FocMainWindow::tcp_ready_read()
{
    while(this->tcp_socket->bytesAvailable() > 0) {
        if(nullptr != this->parser) {
            QByteArray temp_data = this->tcp_socket->readAll();
            parser_add_data(this->parser, (cm_uint8 *)temp_data.data(), temp_data.size());
        }
    }
}

void FocMainWindow::tcp_server_connect()
{
    this->tcp_socket = this->tcp_server->nextPendingConnection();
    connect(this->tcp_socket, SIGNAL(connected()),  this, SLOT(tcp_connected()));
    connect(this->tcp_socket, SIGNAL(disconnected()), this, SLOT(tcp_disconnected()));
    // connect(this->tcp_socket , SIGNAL(stateChanged()), this, SLOT(tcp_state_changed()));
    connect(this->tcp_socket, SIGNAL(readyRead()), this, SLOT(tcp_ready_read()));
}

/**
 * @brief 处理通信连接
 */
void FocMainWindow::slot_connect_deal()
{
    err_code err;

    if(!QString::compare(ui->pb_start_connect->text(), "断开连接")) {
        ui->pb_start_connect->setText("开始连接");
        if(nullptr != this->parser) {
            parser_clean_data(this->parser);
        }
    } else {
        ui->pb_start_connect->setText("断开连接");
        /* 协议处理 */
        if(nullptr != this->parser) {
            parser_clean_data(this->parser);
        } else {
            this->parser = parser_init(MAX_MESSAGE_LEN, &err);
        }

        /* 连接方式处理 */
        if(!QString::compare(ui->cbb_connect_method->currentText(), "串口连接")) {
            std::cout << "当前连接方式串口" << std::endl;

            if(nullptr == this->serial) {
                this->serial = new QSerialPort(this);
            }
        } else if(!QString::compare(ui->cbb_connect_method->currentText(), "TCP 连接")) {
            if(nullptr == this->tcp_server) {
                this->tcp_server = new QTcpServer(this);
            }

            this->tcp_server->listen(QHostAddress::Any, ui->sb_tcp_port->value());   
            connect(this->tcp_server, SIGNAL(newConnection()) ,this , SLOT(tcp_server_connect()));   
        }
    }
}

void FocMainWindow::slot_connect_method_changed(const QString &method)
{
    if(!QString::compare(method, "串口连接")) {
        ui->gb_serial_connect->setEnabled(true);
        ui->gb_tcp_connect->setEnabled(false);

        ui->cbb_serial_port->clear();
        foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
            if(nullptr == this->serial) {
                this->serial = new QSerialPort(this);
            }

            this->serial->setPort(info);
            ui->cbb_serial_port->addItem(this->serial->portName());
        }
    } else if (!QString::compare(method, "TCP 连接")) {
        ui->gb_tcp_connect->setEnabled(true);
        ui->gb_serial_connect->setEnabled(false);

        ui->cbb_tcp_ip->clear();
        /* 获取所有 ip */
        QList<QHostAddress> all_ip = QNetworkInterface::allAddresses();
        for (QList<QHostAddress>::iterator it = all_ip.begin(); it != all_ip.end(); ++it) {
            QHostAddress addr = *it;
            if (addr.protocol() == QAbstractSocket::IPv4Protocol) {
                QString ip = addr.toString();
                ui->cbb_tcp_ip->addItem(ip);
            }
        }
    }
    
}

void FocMainWindow::protocol_timer_out()
{
    // qInfo() << "enter";
    std::cout << "enter " << std::endl;
    if(nullptr != this->parser) {

    }
}

/**
 * @brief  初始化信号与槽
 */
void FocMainWindow::init_signal_and_slot()
{
   connect(ui->pb_start_connect, SIGNAL(clicked()), this, SLOT(slot_connect_deal()));
   connect(ui->cbb_connect_method, SIGNAL(currentTextChanged(QString)), this, SLOT(slot_connect_method_changed(QString)));
   connect(this->protocol_tim, SIGNAL(timeout()), this, SLOT(protocol_timer_out()));
}

FocMainWindow::~FocMainWindow()
{
    if(nullptr != this->parser) {
        this->parser = parser_uninit(this->parser);
    }
    delete ui;
}

